//
//  UnderLineTextField.swift
//  FuXingApp
//
//  Created by zqw on 2021/8/2.
//

import UIKit

let UnderLineTextFieldMainColor = UIColor.init(hex: "#000000")?.withAlphaComponent(0.1)

class UnderLineTextField: UITextField {

    // 添加下划线
    override func draw(_ rect: CGRect) {
        //线条的高度
        let lineHeight : CGFloat = 1
        //线条的颜色
//        let lineColor = UIColor.init(red: 0.93, green: 0.95, blue: 1, alpha: 1)
        let lineColor = UnderLineTextFieldMainColor
        
        
        guard let content = UIGraphicsGetCurrentContext() else { return }
        content.setFillColor(lineColor!.cgColor)
        content.fill(CGRect.init(x: 0, y: self.frame.height - lineHeight, width: self.frame.width, height: lineHeight))
        UIGraphicsBeginImageContextWithOptions(rect.size, true, 0)
    }
    
    override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
        var rect = super.leftViewRect(forBounds: bounds)
        rect.origin.x += 15; //像右边偏15
        return rect;
    }
    
    
    /// 输入限制数量
    var maxLenght: Int = 0
    func textFieldInit(limitLength: Int,holder: String)  {
        maxLenght = limitLength
        //默认设置
        self.attributedPlaceholder = NSAttributedString(string: holder, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16),NSAttributedString.Key.foregroundColor:UnderLineTextFieldMainColor as Any])
    }
    /// 可自定义设置placeholder
    func textFieldInitWithPlaceholder(limitLength: Int,holder: String,holderFont: UIFont,holderColor: UIColor)  {
        maxLenght = limitLength
        self.attributedPlaceholder = NSAttributedString(string: holder, attributes: [NSAttributedString.Key.font: holderFont,NSAttributedString.Key.foregroundColor:holderColor])
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addNotification()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    //添加监听
    func addNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(textFieldTextChanged(sender:)), name: NSNotification.Name("UITextFieldTextDidChangeNotification"), object: self)
    }
    //内容改变时通知响应
    @objc func textFieldTextChanged(sender: Notification) {
        /**
         输入中文拼音时会有markText
         只有当markText为空时才能对Field的text进行筛选处理
         */

        guard let _ = self.markedTextRange else {
            //需要获取当前光标的位置 后面筛选操作后需要进行修改
            let cursorP = self.offset(from: self.endOfDocument, to: self.selectedTextRange!.end)
            //判断非中文的正则表达式
            let pattern = "[\\u4e00-\\u9fa5]"
//            非中文：[^\\u4E00-\\u9FA5]
//            非英文：[^A-Za-z]
//            非数字：[^0-9]
//            非中文或英文：[^A-Za-z\\u4E00-\\u9FA5]
//            非英文或数字：[^A-Za-z0-9]
            
            //替换后的字符串（过滤调非中文字符）
            var str = self.text!.pregReplace(pattern: pattern, with: "")
            
            //textField控制字数限制
            if str.count > maxLenght {
                str = String(str.prefix(maxLenght))
            }
            self.text = str

            //进行光标位置调整
            let newCursorP = self.position(from: self.endOfDocument, offset: cursorP)!
            self.selectedTextRange = self.textRange(from: newCursorP, to: newCursorP)
            return
        }
    
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // 禁止粘贴复制全选等
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        return false
    }
    
}

extension String {
    //使用正则表达式替换
    func pregReplace(pattern: String, with: String,
                     options: NSRegularExpression.Options = []) -> String {
        let regex = try! NSRegularExpression(pattern: pattern, options: options)
        return regex.stringByReplacingMatches(in: self, options: [],
                                              range: NSMakeRange(0, self.count),
                                              withTemplate: with)
    }
}
